# main.py (主程序)
import sys
import os
from secure_config import SecureConfigLoader
from logger import configure_logger
from new_webscroll_capture import WebScrollCapturer
from scheduler import JobScheduler
from image_sender import SyncQyWechatBot
import logging
import time


if __name__ == "__main__":
    # 初始化配置
    config = SecureConfigLoader.load("config.yaml")
    configure_logger(config['app']['log_path'])

    # 启动监控指标
    scheduler = JobScheduler(config)
    # 启动图片机器人
    bot = SyncQyWechatBot(config)

    for task in config['tasks']:
        # 创建截图器实例
        capturer = WebScrollCapturer(task, config)

        # capturer.capture()  # 手动执行验证截图功能  test 测试截图功能是打开注释
        # 从配置中获取任务ID
        task_id = task.get('task_id', f"{task['name']}_capture")
        # 定时截图
        # 添加截图任务调度
        scheduler.add_job(
            capturer.capture,
            trigger_type=task['schedules']['capture']['type'],
            task_id=task_id,
            **task['schedules']['capture'][task['schedules']['capture']['type']]
        )

        # 图片路径
        img_path = os.path.join(
            task['webscroll_capture']['save_dir'],
            task['webscroll_capture']['output_path']
        )

        # 添加发送图片任务调度
        bot.schedule_image_task(
            img_path,
            schedule_config=task['schedules']['send']
        )
    # 注册信号处理
    import signal
    signal.signal(signal.SIGTERM, lambda *_: scheduler.shutdown())
    scheduler.start()

    try:
        # 保持主线程活跃
        while True:
            time.sleep(3600)  # 每小时检查一次
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
        logging.info("程序正常退出")


